package dormouse.vfs.ui.renderers;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;

import dormouse.vfs.ui.JAICanvas;

/**
 * This component is capable of rendering an image.
 * 
 * @author Mark
 *
 */
public class ImageRenderer extends JAICanvas implements IFileRenderer {

    /**
	 * 
	 */
	private static final long serialVersionUID = -3174519854881832809L;
	private static final String[] EXTS = {"jpg", "jpeg", "png", "gif", "tif", "tiff"};

    /**
     * Constructor
     */
    public ImageRenderer() {
        super();
    }

    /**
     * {@inheritDoc }
     */
    public void render(FileObject file) {
        try {

            if (file.getType() == FileType.FILE) {
                BufferedImage image = null;
                try {
                    // Read from an input stream
                    image = ImageIO.read(file.getContent().getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                BufferedImage scaledImage = scaleImage(image, this.getSize());
                this.set(scaledImage);
            }
        } catch (FileSystemException ex) {
            Logger.getLogger(ImageRenderer.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public BufferedImage scaleImage(BufferedImage img, Dimension dim) {
        BufferedImage scaledImg = null;
        AffineTransform tx = new AffineTransform();
        double scalex = dim.getWidth() / img.getWidth();
        double scaley = dim.getHeight() / img.getHeight();
        tx.scale(scalex, scaley);

        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        scaledImg = op.filter(img, null);

        return scaledImg;
    }

    public String[] getFileExtensions() {
        return EXTS;
    }

    public Component getComponent() {
        return this;
    }
}
